<?php
/**
 * Description of conexionclass
 *
 * @author Carlos Mendoza
 */
class Conexion {
    var $motor_base;
    var $servidor;
    var $base;
    var $usuario;
    var $password;
    var $err_msg;
    var $CONNECTED = false;
    var $conexion;
    var $result;

    /**
     *
     * @param <string> $motor_base
     * @param <string> $usuario
     * @param <string> $password
     * @param <string> $base
     * @param <string> $servidor
     * @param <int> $flags
     * @return <boolean> se conectó o no
     */
    function  __construct($motor_base, $usuario = "", $password = "", $base = "", $servidor = "", $flags = "", $encoding = "utf8") {
        if(empty($user) && empty($password) && empty($base) && empty($servidor)){
            $this->err_msg = "No se encontraron par&aacute;metros de conexi&oacute;n a la base";
            return false;
        }else{
            $this->motor_base = $motor_base;
            $this->usuario = $usuario;
            $this->password = $password;
            $this->base = $base;
            $this->servidor = $servidor;

            switch($this->motor_base){
                case "mysql":
                    try{
                        if(!empty($flags))
                            $this->conexion = mysql_connect($servidor,$usuario,$password,0,$flags);
                        else
                            $this->conexion = @mysql_connect($servidor,$usuario,$password);
                        if (!$this->conexion){
                            $this->CONNECTED = false;
                            throw new Exception('Conexion::Conexion: ' . mysql_error());
                            return false;
                        }else{
                            $this->CONNECTED = true;
                            @mysql_select_db($base,$this->conexion);
                            @mysql_set_charset($encoding);
                        }
                    }catch(Exception $e){
                        $this->err_msg = $e->getMessage();
                        $this->CONNECTED = false;
                        return false;
                    }
                    break;
                case "mssql":
                    try{
                        $this->conexion = @mssql_connect($servidor, $usuario, $password);
                        
                        if (!$this->conexion){
                            //throw new Exception('Conexion::Constructor: ' . mssql_get_last_message());
                            $this->err_msg = mssql_get_last_message();
                            $this->CONNECTED = false;
                        }else{
                            mssql_select_db($base, $this->conexion);
                            $this->CONNECTED = true;
                        }
                    }catch(Exception $e){
                        $this->err_msg = $e->getMessage()." ".mssql_get_last_message();
                        $this->CONNECTED = false;
                    }
                    break;
            }
            return true;
        }
    }

    /**
     *
     * @param <string> $query
     * @param <mixed> $param1
     * @param <mixed> $param2
     * @param <mixed> $param3
     * @param <mixed> $param4
     * @param <mixed> $param5
     * @return <boolean> Se ejecutó o no
     */
    public function EjecutarQuery($query, $param1 = "", $param2 = "", $param3 = "", $param4 = "", $param5 = ""){
        //$this->result = null;
        if(!empty ($query)){
            switch($this->motor_base){
                case "mysql":
                    if(!empty($param1) && !empty($param2) && !empty($param3) && !empty ($param4) && !empty ($param5))
                        $query = sprintf($query,
                                mysql_real_escape_string($param1),
                                mysql_real_escape_string($param2),
                                mysql_real_escape_string($param3),
                                mysql_real_escape_string($param4),
                                mysql_real_escape_string($param5));
                    elseif(!empty($param1) && !empty($param2) && !empty($param3) && !empty ($param4))
                        $query = sprintf($query,
                                mysql_real_escape_string($param1),
                                mysql_real_escape_string($param2),
                                mysql_real_escape_string($param3),
                                mysql_real_escape_string($param4));
                    elseif(!empty($param1) && !empty($param2) && !empty($param3))
                        $query = sprintf($query,
                                mysql_real_escape_string($param1),
                                mysql_real_escape_string($param2),
                                mysql_real_escape_string($param3));
                    elseif(!empty($param1) && !empty($param2))
                        $query = sprintf($query,
                                mysql_real_escape_string($param1),
                                mysql_real_escape_string($param2));
                    elseif(!empty($param1))
                        $query = sprintf($query,
                                mysql_real_escape_string($param1));
                    //else $query = mysql_escape_string($query);
//echo $query;
                    $result = @mysql_query($query, $this->conexion);
                    if($result === FALSE){
                        $this->err_msg = 'Conexion::EjecutarQuery: ' . mysql_error();
                        return FALSE;
                    }else{
                        $this->result =& $result;
                        return TRUE;
                    }
                    break;
                case "mssql":
                    if(!empty($param1) && !empty($param2) && !empty($param3) && !empty ($param4) && !empty ($param5))
                        $query = sprintf($query, $param1, $param2, $param3, $param4, $param5);
                    elseif(!empty($param1) && !empty($param2) && !empty($param3) && !empty ($param4))
                        $query = sprintf($query, $param1, $param2, $param3, $param4);
                    elseif(!empty($param1) && !empty($param2) && !empty($param3))
                        $query = sprintf($query, $param1, $param2, $param3);
                    elseif(!empty($param1) && !empty($param2))
                        $query = sprintf($query, $param1, $param2);
                    elseif(!empty($param1))
                        $query = sprintf($query, $param1);
                    $result =& mssql_query($query, $this->conexion);
                    if($result === FALSE){
                        $this->err_msg = 'Conexion::EjecutarQuery: ' .mssql_get_last_message();
                        return FALSE;
                    }else{
                        $this->result =& $result;
                        return TRUE;
                    }
                    break;
            }
        }
    }

    /**
     *
     * @param <string> $sp_name
     * @param <array> $params
     * @return <type>
     *
     * $sp_name es el nombre del procedure solamente
     * $params es un arreglo que tiene la siguiente estructura:
     * array(
     *      nombre de la variable en el procedure,
     *      valor de la variable,
     *      tipo de variable,
     *      longitud máxima
     * )
     */
    public function EjecutarProcedure($sp_name, $params){
        $exito = FALSE;
        if($this->conexion != false && !empty ($sp_name)){
            switch($this->motor_base){
                case "mysql":
                    $str_params = "(";
                    if(count($params) > 0){
                        $cont = 0;
                        foreach ($params as $param){
                            switch($param[2]){
                                case "int":
                                case "float":
                                case "double":
                                    $str_params .= $param[1];
                                    break;
                                case "string":
                                case "time":
                                case "timestamp":
                                case "date":
                                    $str_params .= "'$param[1]'";
                                    break;
                            }
                            
                            $cont++;
                            if($cont < count($params))
                                $str_params .= ",";
                        }

                    }
                    $str_params .= ")";
                    $query = "CALL $sp_name".$str_params;
//echo $query."<br>";
                    $exito = $this->EjecutarQuery($query);
                    break;
                case "mssql":
                    if(count($params) > 0){
                        $proc = mssql_init($sp_name, $this->conexion);
                        foreach($params as $param){
                            switch($param[2]){
                                case "string":
                                case "date":
                                case "time":
                                case "timestamp":
                                case "image":
                                    $type = SQLVARCHAR;
                                    break;
                                case "int":
                                    $type = SQLINT4;
                                    break;
                                case "smallint":
                                    $type = SQLINT2;
                                    break;
                                case "float":
                                case "money":
                                    $type = SQLFLT8;
                                    break;
                                case "text":
                                    $type = SQLTEXT;
                                    break;
                            }
                            mssql_bind($proc, "@".$param[0], $param[1], $type);
                            //mssql_bind($stmt, $param_name, $var, $type, $is_output, $is_null, $maxlen);
                        }
                        $result = mssql_execute($proc);

                        if($result === FALSE){
                            $this->err_msg = 'Conexion::EjecutarProcedure: ' . mssql_get_last_message();
                            $exito = FALSE;
                        }else{
                            $this->result = $result;
                            $exito = TRUE;
                        }
                    }
                    break;
            }
        }
        return $exito;
    }

    public function EjecutarTransaccion($arrQueries){
        switch($this->motor_base){
            case "mysql":
                $commit = true;
                $this->EjecutarQuery("BEGIN");
                foreach($arrQueries as $query){
                    if(!$this->EjecutarQuery($query)){
                        //$this->err_msg = $this->getErrorMessage();
                        echo $this->getErrorMessage();
                        $this->EjecutarQuery("ROLLBACK");
                        $commit = false;
                        break;
                    }
                }
                if($commit)
                    $this->EjecutarQuery("COMMIT");
                break;
        }
        return $commit;
    }

    public function GrabaImagen($SQL,$Campo,$Archivo){
        /*switch($this->motor_base){
            case "mysql":
                break;
        }
        $sql = "insert into sb_imagenes ()";*/
    }

    /**
     *
     * @return <array> que contiene las cabeceras de la consulta realizada
     */
    public function getHeaders(){
        $headers = array();
        switch($this->motor_base){
            case "mysql":
                for($i = 0; $i < mysql_num_fields($this->result); $i++){
                    array_push($headers, mysql_field_name($this->result, $i));
                }
                break;
            case "mssql":
                for($i = 0; $i < mssql_num_fields($this->result); $i++){
                    array_push($headers, mssql_field_name($this->result, $i));
                }
                break;
        }
        return $headers;
    }

    /**
     *
     * @param <string> $DB_FETCH_MODE La forma en que se recupera los datos
     *                 Los valores posibles son: ASSOC, NUM, OBJECT
     * @return <array> Arreglo con los datos recuperados
     */
    public function getData($DB_FETCH_MODE = "ASSOC"){
        $arrData = array();
        switch($this->motor_base){
            case "mysql":
                if($DB_FETCH_MODE == "ASSOC"){
                    while($row = @mysql_fetch_assoc($this->result))
                        array_push($arrData, $row);
                }elseif($DB_FETCH_MODE == "NUM") {
                    while($row = @mysql_fetch_row($this->result))
                        array_push($arrData, $row);
                }else{
                    while($row = @mysql_fetch_object($this->result))
                        array_push($arrData, $row);
                }
                break;
            case "mssql":
                if($DB_FETCH_MODE == "ASSOC"){
                    while($row = mssql_fetch_assoc($this->result))
                        array_push($arrData, $row);
                }elseif($DB_FETCH_MODE == "NUM") {
                    while($row = mssql_fetch_row($this->result))
                        array_push($arrData, $row);
                }else{
                    while($row = mssql_fetch_object($this->result))
                        array_push($arrData, $row);
                }
                break;
        }
        return $arrData;
    }

    /**
     * Cierra la conexión con la base
     */
    public function Cerrar()
    {
        if ($this->CONNECTED)
        {
            switch($this->motor_base){
                case "mysql":
                    @mysql_close($this->conexion);
                    break;
                case "mssql":
                    @mssql_close($this->conexion);
                    break;
            }
            $this->CONNECTED = false;
        }
    }

    /**
     * Retorna el mensaje de error lanzado por la base
     * @return <string>
     */
    public function getErrorMessage(){
        return $this->err_msg;
    }

    /**
     *
     * @return <boolean>
     */
    public function hayError(){
        return $this->hay_error;
    }

    public function liberarResultado(){
        switch($this->motor_base){
            case "mysql":
                @mysql_free_result($this->result);
                break;
            case "mssql":
                @mssql_free_result($this->result);
                break;
        }
    }
}
?>
